package com.dengyuanke.common.log.aspect;

import com.dengyuanke.common.log.annotation.SysLog;
import com.dengyuanke.common.log.event.SysLogEvent;
import com.dengyuanke.common.log.util.SysLogUtils;
import com.dengyuanke.upms.domain.entity.Log;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dyk
 * Create time: 2019-07-13  11:22
 */
@Slf4j
@Aspect
@AllArgsConstructor
public class SysLogAspect {

    private final ApplicationEventPublisher publisher;


    @SneakyThrows
    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint point, SysLog sysLog){
        String strClassName = point.getTarget().getClass().getName();
        String strMethodName = point.getSignature().getName();
        log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

        Log log = SysLogUtils.getSysLog();
        log.setDescription(sysLog.value());

        Long startTime = System.currentTimeMillis();
        Object obj = point.proceed();
        Long endTime = System.currentTimeMillis();
        log.setTime(endTime - startTime);
        publisher.publishEvent(new SysLogEvent(log));
        return obj;
    }
}
